<template>
  <div class="home-page">
    <!-- 系统概览卡片 -->
    <OverviewCards
      :user-stats="homeData.userStats"
      :task-stats="homeData.taskStats"
      :tool-stats="homeData.toolStats"
      :system-stats="homeData.systemStats"
    />

    <!-- 主要内容区域 -->
    <el-row :gutter="24">
      <!-- 数据图表 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
        <div class="chart-container">
          <div class="section-header">
            <h3 class="section-title">
              <span class="chart-icon">📊</span>
              数据统计
            </h3>
            <div class="header-actions">
              <el-button-group>
                <el-button :type="activeChart === 'trend' ? 'primary' : ''" size="small" @click="activeChart = 'trend'">
                  趋势图
                </el-button>
                <el-button
                  :type="activeChart === 'distribution' ? 'primary' : ''"
                  size="small"
                  @click="activeChart = 'distribution'"
                >
                  分布图
                </el-button>
              </el-button-group>
              <el-button :icon="Refresh" size="small" @click="handleRefresh">刷新</el-button>
            </div>
          </div>
          <div class="chart-content">
            <ECharts v-if="activeChart === 'trend'" :option="trendChartOptions" />
            <ECharts v-else :option="distributionChartOptions" />
          </div>
        </div>
      </el-col>

      <!-- 快速访问 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
        <QuickAccess :quick-access-items="homeData.quickAccessItems" />
      </el-col>
    </el-row>

    <!-- 底部内容区域 -->
    <el-row :gutter="24" style="margin-top: 24px">
      <!-- 最近活动 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <div class="activity-container">
          <div class="section-header">
            <h3 class="section-title">
              <el-icon><Clock /></el-icon>
              最近活动
            </h3>
            <div class="header-actions">
              <el-button text @click="viewAllActivities">
                查看全部
                <el-icon><ArrowRight /></el-icon>
              </el-button>
              <el-button :icon="Refresh" text @click="handleRefresh">刷新</el-button>
            </div>
          </div>
          <div class="activity-list">
            <div v-for="activity in homeData.recentActivities.slice(0, 8)" :key="activity.id" class="activity-item">
              <div class="activity-avatar">
                <el-avatar :size="32">
                  {{ activity.userName.charAt(0) }}
                </el-avatar>
              </div>
              <div class="activity-content">
                <div class="activity-title">
                  <span class="user-name">{{ activity.userName }}</span>
                  <span class="action">{{ activity.description }}</span>
                </div>
                <div class="activity-meta">
                  <el-tag :type="getActivityTagType(activity.type)" size="small">
                    {{ getActivityTypeLabel(activity.type) }}
                  </el-tag>
                  <span class="timestamp">{{ formatTime(activity.timestamp) }}</span>
                </div>
              </div>
            </div>
            <div v-if="homeData.recentActivities.length === 0" class="empty-state">
              <el-empty description="暂无活动记录" :image-size="100" />
            </div>
          </div>
        </div>
      </el-col>

      <!-- 系统通知 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
        <div class="notification-container">
          <div class="section-header">
            <h3 class="section-title">
              <el-icon><Bell /></el-icon>
              系统通知
              <el-badge v-if="unreadCount > 0" :value="unreadCount" class="notification-badge" />
            </h3>
            <div class="header-actions">
              <el-button text @click="markAllAsRead"> 全部已读 </el-button>
              <el-button :icon="Refresh" text @click="handleRefresh">刷新</el-button>
            </div>
          </div>
          <div class="notification-list">
            <div
              v-for="notification in homeData.notifications.slice(0, 6)"
              :key="notification.id"
              :class="['notification-item', { unread: !notification.isRead }]"
              @click="handleNotificationClick(notification)"
            >
              <div class="notification-icon">
                <el-icon :color="getNotificationColor(notification.type)" :size="16">
                  <component :is="getNotificationIcon(notification.type)" />
                </el-icon>
              </div>
              <div class="notification-content">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-text">{{ notification.content }}</div>
                <div class="notification-time">{{ formatTime(notification.createTime) }}</div>
              </div>
              <div class="notification-priority">
                <el-tag :type="getPriorityTagType(notification.priority)" size="small">
                  {{ notification.priority }}
                </el-tag>
              </div>
            </div>
            <div v-if="homeData.notifications.length === 0" class="empty-state">
              <el-empty description="暂无通知消息" :image-size="100" />
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 最后更新时间 -->
    <div class="update-info">
      <el-text type="info" size="small">
        <el-icon><Refresh /></el-icon>
        最后更新：{{ formatTime(lastUpdateTime) }}
      </el-text>
    </div>
  </div>
</template>

<script setup lang="ts" name="home">
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Clock, Bell, ArrowRight, Refresh, InfoFilled, WarningFilled, CircleCheck, Promotion } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import "dayjs/locale/zh-cn";

// 组件导入
import OverviewCards from "./components/OverviewCards.vue";
import QuickAccess from "./components/QuickAccess.vue";
import ECharts from "@/components/ECharts/index.vue";

// Hooks 导入
import { useHomeData } from "./hooks/useHomeData";

// 类型导入
import type { NotificationItem, ActivityRecord } from "./types/home";

// 配置 dayjs
dayjs.extend(relativeTime);
dayjs.locale("zh-cn");

const router = useRouter();
const { homeData, lastUpdateTime, initData, refreshData } = useHomeData();

// 图表状态
const activeChart = ref<"trend" | "distribution">("trend");

// 未读通知数量
const unreadCount = computed(() => {
  return homeData.notifications.filter(n => !n.isRead).length;
});

// 趋势图配置
const trendChartOptions = computed(() => ({
  title: {
    text: "用户登录情况",
    left: "left",
    textStyle: {
      fontSize: 14,
      fontWeight: 600
    }
  },
  tooltip: {
    trigger: "axis" as const
  },
  xAxis: {
    type: "category" as const,
    boundaryGap: false,
    data: homeData.chartData.userGrowthTrend.dates,
    axisLine: {
      lineStyle: {
        color: "#e4e7ed"
      }
    }
  },
  yAxis: {
    type: "value" as const,
    axisLine: {
      lineStyle: {
        color: "#e4e7ed"
      }
    }
  },
  series: [
    {
      data: homeData.chartData.userGrowthTrend.values,
      type: "line" as const,
      smooth: true,
      areaStyle: {
        color: {
          type: "linear" as const,
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: "rgba(64, 158, 255, 0.3)"
            },
            {
              offset: 1,
              color: "rgba(64, 158, 255, 0.1)"
            }
          ]
        }
      },
      lineStyle: {
        color: "#409EFF"
      },
      itemStyle: {
        color: "#409EFF"
      }
    }
  ],
  grid: {
    left: "1%",
    right: "1%",
    bottom: "1%",
    containLabel: true
  }
}));

// 分布图配置
const distributionChartOptions = computed(() => ({
  title: {
    text: "功能模块使用分布",
    left: "left",
    textStyle: {
      fontSize: 14,
      fontWeight: 600
    }
  },
  tooltip: {
    trigger: "item" as const,
    formatter: "{a} <br/>{b}: {c} ({d}%)"
  },
  series: [
    {
      name: "使用量",
      type: "pie" as const,
      radius: ["40%", "70%"],
      center: ["50%", "60%"],
      data: homeData.chartData.moduleUsageDistribution,
      itemStyle: {
        borderRadius: 8,
        borderColor: "#fff",
        borderWidth: 2
      },
      label: {
        show: true,
        formatter: "{b}: {d}%"
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)"
        }
      }
    }
  ]
}));

// 格式化时间
const formatTime = (time: string | Date) => {
  if (!time) return "";
  return dayjs(time).fromNow();
};

// 获取活动类型标签类型
const getActivityTagType = (type: ActivityRecord["type"]) => {
  const typeMap = {
    login: "success",
    operation: "primary",
    system: "warning",
    task: "info"
  };
  return typeMap[type] || "info";
};

// 获取活动类型标签
const getActivityTypeLabel = (type: ActivityRecord["type"]) => {
  const labelMap = {
    login: "登录",
    operation: "操作",
    system: "系统",
    task: "任务"
  };
  return labelMap[type] || "未知";
};

// 获取通知图标
const getNotificationIcon = (type: NotificationItem["type"]) => {
  const iconMap = {
    announcement: InfoFilled,
    warning: WarningFilled,
    reminder: CircleCheck,
    update: Promotion
  };
  return iconMap[type] || InfoFilled;
};

// 获取通知颜色
const getNotificationColor = (type: NotificationItem["type"]) => {
  const colorMap = {
    announcement: "#409EFF",
    warning: "#E6A23C",
    reminder: "#67C23A",
    update: "#F56C6C"
  };
  return colorMap[type] || "#409EFF";
};

// 获取优先级标签类型
const getPriorityTagType = (priority: NotificationItem["priority"]) => {
  const typeMap = {
    high: "danger",
    medium: "warning",
    low: "info"
  };
  return typeMap[priority] || "info";
};

// 查看全部活动
const viewAllActivities = () => {
  router.push("/system/userAction");
};

// 标记全部已读
const markAllAsRead = () => {
  homeData.notifications.forEach(notification => {
    notification.isRead = true;
  });
  ElMessage.success("已标记全部通知为已读");
};

// 处理通知点击
const handleNotificationClick = (notification: NotificationItem) => {
  notification.isRead = true;
  // 这里可以添加跳转到具体通知详情的逻辑
  ElMessage.info("查看通知详情");
};

// 刷新数据
const handleRefresh = async () => {
  await refreshData();
  ElMessage.success("数据已刷新");
};

// 组件挂载时初始化数据
onMounted(async () => {
  await initData();
  console.log(homeData.notifications);
});
</script>

<style scoped lang="scss">
.home-page {
  min-height: 100vh;
  padding: 10px;
  background: var(--el-bg-color-page);
  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    .section-title {
      display: flex;
      gap: 8px;
      align-items: center;
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      .el-icon {
        color: var(--el-color-primary);
      }
      .chart-icon {
        font-size: 18px;
        color: var(--el-color-primary);
      }
      .notification-badge {
        margin-left: 8px;
      }
    }
    .header-actions {
      display: flex;
      gap: 8px;
      align-items: center;
    }
  }
  .chart-container,
  .activity-container,
  .notification-container {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 300px;
    padding: 24px;
    background-color: var(--el-bg-color);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 12px;
    box-shadow: 0 2px 12px rgb(0 0 0 / 10%);
  }
  .chart-content {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 100%;
    margin-top: 16px;
  }
  .activity-list,
  .notification-list {
    max-height: 400px;
    overflow-y: auto;
  }
  .activity-item {
    display: flex;
    gap: 12px;
    align-items: flex-start;
    padding: 12px 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
    transition: background-color 0.3s ease;
    &:last-child {
      border-bottom: none;
    }
    &:hover {
      padding: 12px;
      margin: 0 -12px;
      background: var(--el-bg-color-page);
      border-radius: 8px;
    }
    .activity-avatar {
      flex-shrink: 0;
    }
    .activity-content {
      flex: 1;
      min-width: 0;
      .activity-title {
        margin-bottom: 6px;
        .user-name {
          font-weight: 600;
          color: var(--el-text-color-primary);
        }
        .action {
          margin-left: 4px;
          color: var(--el-text-color-regular);
        }
      }
      .activity-meta {
        display: flex;
        gap: 8px;
        align-items: center;
        .timestamp {
          font-size: 12px;
          color: var(--el-text-color-placeholder);
        }
      }
    }
  }
  .notification-item {
    display: flex;
    gap: 12px;
    align-items: flex-start;
    padding: 12px;
    margin-bottom: 8px;
    cursor: pointer;
    border: 1px solid transparent;
    border-radius: 8px;
    transition: all 0.3s ease;
    &:hover {
      background: var(--el-bg-color-page);
      border-color: var(--el-border-color);
    }
    &.unread {
      background: var(--el-color-primary-light-9);
      border-color: var(--el-color-primary-light-7);
    }
    .notification-icon {
      flex-shrink: 0;
      margin-top: 2px;
    }
    .notification-content {
      flex: 1;
      min-width: 0;
      .notification-title {
        margin-bottom: 4px;
        font-size: 14px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
      .notification-text {
        display: -webkit-box;
        margin-bottom: 6px;
        overflow: hidden;
        font-size: 13px;
        color: var(--el-text-color-regular);
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      .notification-time {
        font-size: 12px;
        color: var(--el-text-color-placeholder);
      }
    }
    .notification-priority {
      flex-shrink: 0;
    }
  }
  .empty-state {
    padding: 40px 20px;
    text-align: center;
  }
  .update-info {
    padding: 16px;
    margin-top: 24px;
    text-align: center;
    .el-text {
      display: flex;
      gap: 4px;
      align-items: center;
      justify-content: center;
    }
  }
}

// 响应式设计
@media (width <= 768px) {
  .home-page {
    padding: 16px;
    .chart-container,
    .activity-container,
    .notification-container {
      padding: 16px;
    }
    .section-header {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
      .section-title {
        font-size: 16px;
      }
    }
    .activity-item,
    .notification-item {
      gap: 8px;
      padding: 8px;
    }
  }
}

@media (width <= 1024px) {
  .home-page {
    .el-row .el-col {
      margin-bottom: 24px;
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>
